import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:esp_blufi/esp_blufi.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _espBlufiPlugin = EspBlufi.instance;
  Map<String, EspDevice> deviceMap = {};
  EspDevice? selectDevice;
  TextEditingController ssidController = TextEditingController();
  TextEditingController pswController = TextEditingController();
  PageController pageController = PageController();
  bool isScaning = false;
  bool isConnected = false;

  @override
  void initState() {
    super.initState();
    ssidController.text = "liboya7";
    pswController.text = "88888888";
    _espBlufiPlugin.onMessageReceived(
      EspBlufiListener(
        onScanResult: (device) {
          if (device.name == null) {
            return;
          }
          deviceMap[device.address!] = device;
          setState(() {});
        },
        onConnectResult: (connectResult) {
          if (connectResult['code'] == EspBlufiCode.success) {
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("设备连接成功")));
            setState(() {
              isConnected = true;
            });
          } else {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("连接失败, code=${connectResult['code']}")));
            setState(() {
              isConnected = false;
            });
          }
        },
        onDeviceStatus: (deviceStatus) {
          if (deviceStatus.code == EspBlufiCode.success) {
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("配网成功")));
          } else {
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("配网失败")));
          }
        },
        onScanWifi: (wifiList) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("检测到${wifiList.length}个wifi")));
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: SafeArea(
        child: PageView(
          controller: pageController,
          physics: const NeverScrollableScrollPhysics(),
          children: [buildFirst(), buildSecondPage()],
        ),
      ),
    );
  }

  Widget buildFirst() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton(
              onPressed: () async{
                bool status = await _espBlufiPlugin.isBluetoothEnabled();
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("蓝牙:${status ? "开" : "关"}")));
              },
              child: const Text("判断蓝牙状态"),
            ),
            ElevatedButton(
                onPressed: isScaning
                    ? null
                    : () async {
                        var result = await checkPermission();
                        if (result != true) {
                          return;
                        }
                        deviceMap.clear();
                        _espBlufiPlugin.scan(filter: "");
                        setState(() {
                          isScaning = true;
                        });
                      },
                child: const Text("扫描")),
            ElevatedButton(
              onPressed: !isScaning
                  ? null
                  : () {
                      _espBlufiPlugin.stopScan();
                      setState(() {
                        isScaning = false;
                      });
                    },
              child: const Text("停止扫描"),
            ),

          ],
        ),
        Expanded(
          child: ListView.separated(
            itemCount: deviceMap.keys.length,
            separatorBuilder: (context, index) {
              return const Divider(
                height: 1,
              );
            },
            itemBuilder: (context, index) {
              var address = deviceMap.keys.toList()[index];
              var device = deviceMap[address];
              return ListTile(
                title: Text(device?.name ?? ""),
                subtitle: Text(address),
                tileColor: selectDevice == device ? Colors.blueGrey : Colors.white,
                onTap: () {
                  _espBlufiPlugin.stopScan();
                  selectDevice = device;
                  isScaning = false;
                  pageController.nextPage(duration: const Duration(milliseconds: 300), curve: Curves.linear);
                  setState(() {});
                },
              );
            },
          ),
        ),
      ],
    );
  }

  Widget buildSecondPage() {
    return Column(
      children: [
        Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
            child: Text("设备名:${selectDevice?.name}")),
        Wrap(
          spacing: 10,
          children: [
            ElevatedButton(
                onPressed: isConnected
                    ? null
                    : () {
                        if (selectDevice == null) {
                          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("选择一个设备")));
                          return;
                        }
                        _espBlufiPlugin.connectDevice(selectDevice!.address!);
                      },
                child: const Text("连接设备")),
            ElevatedButton(
                onPressed: !isConnected
                    ? null
                    : () {
                        if (ssidController.text.isEmpty || pswController.text.isEmpty) {
                          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("输入wifi")));
                          return;
                        }
                        _espBlufiPlugin.configure(ssidController.text, pswController.text);
                      },
                child: const Text("配网")),
            ElevatedButton(
                onPressed: !isConnected
                    ? null
                    : () {
                        _espBlufiPlugin.requestDeviceStatus();
                      },
                child: const Text("状态")),
            ElevatedButton(
                onPressed: !isConnected
                    ? null
                    : () {
                        _espBlufiPlugin.requestDeviceVersion();
                      },
                child: const Text("版本")),
            ElevatedButton(
                onPressed: !isConnected
                    ? null
                    : () {
                        _espBlufiPlugin.requestDeviceWifiScan();
                      },
                child: const Text("wifi列表")),
            ElevatedButton(
                onPressed: () {
                  pageController.previousPage(duration: const Duration(milliseconds: 300), curve: Curves.linear);
                },
                child: const Text("返回")),
          ],
        ),
        Padding(
          padding: const EdgeInsets.all(15.0),
          child: TextField(
            controller: ssidController,
            decoration: const InputDecoration(
              hintText: "Wi-Fi名称",
              border: OutlineInputBorder(),
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(15.0),
          child: TextField(
            controller: pswController,
            decoration: const InputDecoration(
              hintText: "Wi-Fi密码",
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ],
    );
  }

  ///检查权限
  Future<bool> checkPermission() async {
    if (Platform.isAndroid && await Permission.location.isGranted && await Permission.bluetoothScan.isGranted) {
      return true;
    }
    if (Platform.isIOS && await Permission.bluetooth.isGranted) {
      return true;
    }

    List<Permission> permissionList = [
      if (Platform.isAndroid) ...[Permission.bluetoothScan, Permission.bluetoothConnect, Permission.location] else
        Permission.bluetooth
    ];
    Map<Permission, PermissionStatus> statuses = await permissionList.request();
    if (statuses.values.any((element) => !element.isGranted)) {
      return false;
    }

    return true;
  }
}
